//package org.example.common.aop;
//
//import com.google.common.collect.Sets;
//import org.apache.commons.lang3.StringUtils;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.example.common.annotation.RequirePermission;
//import org.example.common.bean.CommonException;
//import org.example.common.enums.LogicEnum;
//import org.springframework.core.annotation.Order;
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import java.util.Set;
//
///**
// * 自定义权限校验注解.
// *
// * @author Jjn
// * @since 2021-10-15 9:24
// */
//@Component
//@Aspect
//@Order(1)
//public class PermissionAspect {
//    private static final String PERMISSION_NOT_SATISFIED = "权限不足";
//    private static final String TOKEN_IS_BLANK = "令牌为空,无法获取用户信息";
//
//    @Resource
//    private UserService userService;
//
//    @Pointcut("@annotation(com.njwx.yq.common.annotation.RequirePermission)")
//    public void pointcutMethod() {
//        // sonar
//    }
//
//    @Around(value = "pointcutMethod()&& @annotation(requirePermission)", argNames = "joinPoint,requirePermission")
//    public Object before(ProceedingJoinPoint joinPoint, RequirePermission requirePermission) throws Throwable {
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        //获取请求的request
//        assert attributes != null;
//        HttpServletRequest request = attributes.getRequest();
//        String authorization = request.getHeader("Authorization");
//        LogicEnum logical = requirePermission.logical();
//        if (StringUtils.isBlank(authorization)) {
//            throw new CommonException(500, TOKEN_IS_BLANK);
//        }
//        String[] requiredPermissions = requirePermission.requiredPermissions();
//        Set<String> required = Sets.newHashSet(requiredPermissions);
//        Set<String> owned = userService.currentUserPermissions();
//        if (logical == LogicEnum.OR) {
//            for (String requiredRole : required) {
//                if (owned.contains(requiredRole)) {
//                    return joinPoint.proceed();
//                }
//            }
//            throw new CommonException(500, PERMISSION_NOT_SATISFIED);
//        }
//        if (logical == LogicEnum.AND) {
//            for (String requiredRole : requiredPermissions) {
//                if (!owned.contains(requiredRole)) {
//                    throw new CommonException(500, PERMISSION_NOT_SATISFIED);
//                }
//            }
//        }
//        return joinPoint.proceed();
//    }
//}
